package com.heima.behavior.compo.impl;

import com.heima.behavior.compo.TianxingApi;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.TianxingVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Objects;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-30 16:26
 */
@Component
@Slf4j
public class TianxingApiImpl implements TianxingApi {

    public static final String TIANXING_TIANGOURIJI_REDIS_KEY = "leadnews:behavior:tiangourji";
    public static final int DATA_NUM = 10;

    @Value("${tianxing.url}")
    public String tianxingUrl;

    @Autowired
    private CacheService cacheService;
    @Autowired
    private RestTemplate restTemplate;

    @Scheduled(cron = "0 0 1 * * ?")
    @PostConstruct //启动时缓存一次舔狗日记
    public void cacheTiangouriji(){
        cacheService.delete(TIANXING_TIANGOURIJI_REDIS_KEY);
//        String tiangourijiLock = cacheService.tryLock("tiangourijiLock", 1000 * 60 * 60);
//        if(tiangourijiLock != null){
            //拿到锁 缓存数据
            for (int i = 0; i < DATA_NUM; i++) {
                cacheTianxingDataToRedis();
            }
//        }

        //判断set中是否有数据，如果没有数据，给默认数据
        Long aLong = cacheService.sSize(TIANXING_TIANGOURIJI_REDIS_KEY);
        if(aLong == null || aLong == 0){
            //没有数据
            cacheService.sAdd(TIANXING_TIANGOURIJI_REDIS_KEY,"昨晚本王和朋友打了一晚上游戏，我破天荒的的给17号舔狗看了战绩，虽然他看不懂但是他相信本王一定是最厉害的，最棒的！他给本王发了好多消息，告诉我有多崇拜我，我回了他一句“啥b”。并不是因为什么，只是刚刚男神给我打电话，叫我去宾馆。哎一晚上整的我死去活来，第二天就给他打电话叫他来接我，才发现他竟然改了ID，“我是你的啥b啊”");
        }
    }

    private void cacheTianxingDataToRedis(){
        try{
            //1.调用天行接口
            TianxingVO forObject =
                    restTemplate.
                            getForObject(tianxingUrl
                                    , TianxingVO.class);
            //2.获取数据保存到redis中
            if(forObject != null && Objects.equals(forObject.getCode(),200)){
                List<TianxingVO.NewslistDTO> newslist = forObject.getNewslist();
                if(!CollectionUtils.isEmpty(newslist)){
                    TianxingVO.NewslistDTO newslistDTO = newslist.get(0);
                    String content = newslistDTO.getContent();
                    cacheService.sAdd(TIANXING_TIANGOURIJI_REDIS_KEY,content);
                }
            }
        }catch (Exception e){
            //异常吃掉
            log.error("调用天行接口失败",e);
        }

    }

    @Override
    public String tiangouriji() {
        return cacheService.sRandomMember(TIANXING_TIANGOURIJI_REDIS_KEY);
    }
}
